<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="springboot,配置参数获取," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="相比Spring项目，SpringBoot中，很多的配置内容都是SpringBoot自动装配。我们明显感知到的就是配置文件的减少。甚至连参数配置文件也一起放在SpringBoot的配置文件中。所以，我们来看下如何获取配置文件中的参数 1通过@Value 注解@Configurationpublic class SpringBootConfiguration&amp;#123;	@Value(&quot;$&amp;#123">
<meta name="keywords" content="springboot,配置参数获取">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot中Environment的使用">
<meta property="og:url" content="https://gitee.com/shuhao/2017/11/22/SpringBoot中Environment的使用/index.html">
<meta property="og:site_name" content="Niki">
<meta property="og:description" content="相比Spring项目，SpringBoot中，很多的配置内容都是SpringBoot自动装配。我们明显感知到的就是配置文件的减少。甚至连参数配置文件也一起放在SpringBoot的配置文件中。所以，我们来看下如何获取配置文件中的参数 1通过@Value 注解@Configurationpublic class SpringBootConfiguration&amp;#123;	@Value(&quot;$&amp;#123">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-11-22T07:38:07.299Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SpringBoot中Environment的使用">
<meta name="twitter:description" content="相比Spring项目，SpringBoot中，很多的配置内容都是SpringBoot自动装配。我们明显感知到的就是配置文件的减少。甚至连参数配置文件也一起放在SpringBoot的配置文件中。所以，我们来看下如何获取配置文件中的参数 1通过@Value 注解@Configurationpublic class SpringBootConfiguration&amp;#123;	@Value(&quot;$&amp;#123">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/shuhao/2017/11/22/SpringBoot中Environment的使用/"/>





  <title> SpringBoot中Environment的使用 | Niki </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cb9f0585e406f878cb2f29c89ad3cdb7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Niki</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天道酬勤</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-categories"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/shuhao/blog/2017/11/22/SpringBoot中Environment的使用/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Fang ShuHao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Niki">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                SpringBoot中Environment的使用
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-11-22T11:06:36+08:00">
                2017-11-22
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/springboot/" itemprop="url" rel="index">
                    <span itemprop="name">springboot</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>相比Spring项目，SpringBoot中，很多的配置内容都是SpringBoot自动装配。我们明显感知到的就是配置文件的减少。甚至连参数配置文件也一起放在SpringBoot的配置文件中。<br>所以，我们来看下如何获取配置文件中的参数</p>
<h2 id="1通过-Value-注解"><a href="#1通过-Value-注解" class="headerlink" title="1通过@Value 注解"></a>1通过@Value 注解</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SpringBootConfiguration</span></span>&#123;</span><br><span class="line">	<span class="meta">@Value</span>(<span class="string">"$&#123;appName&#125;"</span>)</span><br><span class="line">	<span class="keyword">private</span> String param1;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Value</span>(<span class="string">"$&#123;appPort&#125;"</span>)</span><br><span class="line">	<span class="keyword">private</span> <span class="keyword">int</span> port ;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="首先需要-为参数类加上-Configuration的注解，这样SpringBoot就能扫描到配置文件的参数了。然后通过-Value注解将对应的参数注入到类对应变量。"><a href="#首先需要-为参数类加上-Configuration的注解，这样SpringBoot就能扫描到配置文件的参数了。然后通过-Value注解将对应的参数注入到类对应变量。" class="headerlink" title="首先需要 为参数类加上@Configuration的注解，这样SpringBoot就能扫描到配置文件的参数了。然后通过@Value注解将对应的参数注入到类对应变量。"></a>首先需要 为参数类加上@Configuration的注解，这样SpringBoot就能扫描到配置文件的参数了。然后通过@Value注解将对应的参数注入到类对应变量。</h3><h2 id="2-通过-Spring的Environment"><a href="#2-通过-Spring的Environment" class="headerlink" title="2 通过 Spring的Environment"></a>2 通过 Spring的Environment</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">TestServcie</span></span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="meta">@Resource</span></span><br><span class="line">	Environment environment ;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> String <span class="title">getProperties</span><span class="params">(String key)</span></span>&#123;</span><br><span class="line">		<span class="keyword">return</span> environment.getProperty(key);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="3-参数来源"><a href="#3-参数来源" class="headerlink" title="3 参数来源"></a>3 参数来源</h2><h3 id="命令行参数"><a href="#命令行参数" class="headerlink" title="命令行参数"></a>命令行参数</h3><figure class="highlight shell"><table><tr><td class="code"><pre><span class="line"><span class="meta">#</span>运行springboot项目，并且修改载入配置文件的名称为myproject（默认为application）</span><br><span class="line">java -jar myproject.jar --spring.config.name=myproject</span><br><span class="line"></span><br><span class="line"><span class="meta">#</span>运行sprintboot项目，并且修改配置文件的路径，多个以逗号隔开</span><br><span class="line">java -jar myproject.jar --spring.config.location=classpath:/default.properties, classpath:/myproperties.properties</span><br><span class="line"></span><br><span class="line"><span class="meta">#</span>运行springboot项目，修改项目端口号为8888</span><br><span class="line">java -jar myproject.jar --server.port=8888</span><br></pre></td></tr></table></figure>
<p>Spring会将命令行参数保存到Spring的Environment中。可以通过Spring的Environment来访问。<br>当然，也可以通过SpringApplication.setAddCommandLineProperties(false)来禁止</p>
<h3 id="java系统属性"><a href="#java系统属性" class="headerlink" title="java系统属性"></a>java系统属性</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//所有的java系统属性</span></span><br><span class="line">System.getProperties();</span><br><span class="line"></span><br><span class="line"><span class="comment">//查看JVM版本</span></span><br><span class="line">System.getProperty(<span class="string">"java.runtime.version"</span>);</span><br></pre></td></tr></table></figure>
<h3 id="系统环境变量"><a href="#系统环境变量" class="headerlink" title="系统环境变量"></a>系统环境变量</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//所有的系统环境变量</span></span><br><span class="line">System.getenv();</span><br><span class="line"></span><br><span class="line"><span class="comment">//返回PATH变量的值</span></span><br><span class="line">System.getenv(<span class="string">"PATH"</span>);</span><br></pre></td></tr></table></figure>
<h3 id="来源配置文件（properties、yml）"><a href="#来源配置文件（properties、yml）" class="headerlink" title="来源配置文件（properties、yml）"></a>来源配置文件（properties、yml）</h3><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">application.proerties</span><br><span class="line">server.port=8898</span><br><span class="line"></span><br><span class="line">application.yml</span><br><span class="line">server: </span><br><span class="line">    port: 8898</span><br></pre></td></tr></table></figure>
<h2 id="4-配置文件保存目录以及优先级"><a href="#4-配置文件保存目录以及优先级" class="headerlink" title="4 配置文件保存目录以及优先级"></a>4 配置文件保存目录以及优先级</h2><p>在Springboot项目里，我们的配置文件可存放的位置有：<br>project/config</p>
<p>project/src/main/resource</p>
<p>并且config里面的配置文件优先级高于resource目录中的配置文件</p>
<p>配置文件有两种类型.properties 和.yml<br>.properties类型的配置文件优先级高于.yml类型配置文件的优先级</p>
<h1 id="也就是说，在配置文件中配置了同一个属性参数，则会优先读取config目录下的-proerties配置文件中的参数，其次是config目录下的-yml配置文件，然后是resource目录下的-properties，最后才是resource目录下的-yml文件中的参数值"><a href="#也就是说，在配置文件中配置了同一个属性参数，则会优先读取config目录下的-proerties配置文件中的参数，其次是config目录下的-yml配置文件，然后是resource目录下的-properties，最后才是resource目录下的-yml文件中的参数值" class="headerlink" title="也就是说，在配置文件中配置了同一个属性参数，则会优先读取config目录下的.proerties配置文件中的参数，其次是config目录下的.yml配置文件，然后是resource目录下的.properties，最后才是resource目录下的.yml文件中的参数值"></a>也就是说，在配置文件中配置了同一个属性参数，则会优先读取config目录下的.proerties配置文件中的参数，其次是config目录下的.yml配置文件，然后是resource目录下的.properties，最后才是resource目录下的.yml文件中的参数值</h1>
      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/springboot/" rel="tag"># springboot</a>
          
            <a href="/blog/tags/配置参数获取/" rel="tag"># 配置参数获取</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2017/11/20/springboot对Mongo增删改查的方式/" rel="next" title="springboot对Mongo增删改查的方式">
                <i class="fa fa-chevron-left"></i> springboot对Mongo增删改查的方式
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2017/11/28/virtubox虚拟机中Ubuntu系统与系统ping通并且可以用Xshell访问/" rel="prev" title="virtubox虚拟机中Ubuntu系统与系统ping通并且可以用Xshell访问">
                virtubox虚拟机中Ubuntu系统与系统ping通并且可以用Xshell访问 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNjY5NS8xMzIzMA=="></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/head.jpg"
               alt="Fang ShuHao" />
          <p class="site-author-name" itemprop="name">Fang ShuHao</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">135</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories">
                <span class="site-state-item-count">35</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">93</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1通过-Value-注解"><span class="nav-number">1.</span> <span class="nav-text">1通过@Value 注解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#首先需要-为参数类加上-Configuration的注解，这样SpringBoot就能扫描到配置文件的参数了。然后通过-Value注解将对应的参数注入到类对应变量。"><span class="nav-number">1.1.</span> <span class="nav-text">首先需要 为参数类加上@Configuration的注解，这样SpringBoot就能扫描到配置文件的参数了。然后通过@Value注解将对应的参数注入到类对应变量。</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-通过-Spring的Environment"><span class="nav-number">2.</span> <span class="nav-text">2 通过 Spring的Environment</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-参数来源"><span class="nav-number">3.</span> <span class="nav-text">3 参数来源</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#命令行参数"><span class="nav-number">3.1.</span> <span class="nav-text">命令行参数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#java系统属性"><span class="nav-number">3.2.</span> <span class="nav-text">java系统属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#系统环境变量"><span class="nav-number">3.3.</span> <span class="nav-text">系统环境变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#来源配置文件（properties、yml）"><span class="nav-number">3.4.</span> <span class="nav-text">来源配置文件（properties、yml）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-配置文件保存目录以及优先级"><span class="nav-number">4.</span> <span class="nav-text">4 配置文件保存目录以及优先级</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#也就是说，在配置文件中配置了同一个属性参数，则会优先读取config目录下的-proerties配置文件中的参数，其次是config目录下的-yml配置文件，然后是resource目录下的-properties，最后才是resource目录下的-yml文件中的参数值"><span class="nav-number"></span> <span class="nav-text">也就是说，在配置文件中配置了同一个属性参数，则会优先读取config目录下的.proerties配置文件中的参数，其次是config目录下的.yml配置文件，然后是resource目录下的.properties，最后才是resource目录下的.yml文件中的参数值</span></a></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fang ShuHao</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  



  
  

  

  

  

  


  

</body>
</html>
